package com.bigwork.service.impl;

//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bigwork.dto.order.OrderCreateRequest;
import com.bigwork.dto.order.OrderResponse;
import com.bigwork.entity.Order;
import com.bigwork.entity.OrderItem;
import com.bigwork.entity.Product;
import com.bigwork.entity.User;
import com.bigwork.enums.OrderStatus;
import com.bigwork.exception.ResourceNotFoundException;
import com.bigwork.mapper.OrderItemMapper;
import com.bigwork.mapper.OrderMapper;
import com.bigwork.mapper.ProductMapper;
import com.bigwork.mapper.UserMapper;
import com.bigwork.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final UserMapper userMapper;
    private final ProductMapper productMapper;

    @Override
    @Transactional
    public OrderResponse createOrder(OrderCreateRequest request) {
        User user = userMapper.selectById(request.getUserId());
        if (user == null) {
            throw new ResourceNotFoundException("未找到用户ID: " + request.getUserId());
        }

        List<Product> products = productMapper.selectBatchIds(request.getProductIds());
        if (products.size() != request.getProductIds().size()) {
            throw new ResourceNotFoundException("部分商品ID无效");
        }

        Order order = new Order();
        order.setOrderNumber(generateOrderNumber());
        order.setUserId(user.getId());
        order.setStatus(OrderStatus.PENDING_PAYMENT);

        BigDecimal totalPrice = products.stream().map(Product::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        order.setTotalPrice(totalPrice);

        orderMapper.insert(order);

        for (Product product : products) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(product.getId());
            orderItem.setQuantity(1);
            orderItem.setPrice(product.getPrice());
            orderItemMapper.insert(orderItem);
            order.getItems().add(orderItem);
        }

        return OrderResponse.fromEntity(order);
    }

    @Override
    public OrderResponse getOrderDetailsByOrderNumber(String orderNumber) {
        Order order = orderMapper.selectByOrderNumber(orderNumber);
        if (order == null) {
            throw new ResourceNotFoundException("未找到订单号: " + orderNumber);
        }
        order.setItems(orderItemMapper.selectByOrderId(order.getId()));
        return OrderResponse.fromEntity(order);
    }

    @Override
    public List<OrderResponse> getOrdersByUserId(Long userId) {
        if (userMapper.selectById(userId) == null) {
            throw new ResourceNotFoundException("未找到用户ID: " + userId);
        }
        List<Order> orders = orderMapper.selectByUserId(userId);
        return orders.stream()
                .peek(order -> order.setItems(orderItemMapper.selectByOrderId(order.getId())))
                .map(OrderResponse::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public OrderResponse updateOrderStatus(String orderNumber, OrderStatus newStatus) {
        Order order = orderMapper.selectByOrderNumber(orderNumber);
        if (order == null) {
            throw new ResourceNotFoundException("未找到订单号: " + orderNumber);
        }

        order.setStatus(newStatus);
        orderMapper.updateById(order);

        return getOrderDetailsByOrderNumber(orderNumber);
    }

    private String generateOrderNumber() {
        return "ORD-" + Instant.now().toEpochMilli() + "-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }
}